﻿//-----------------------------------------------------------------------
// <copyright file="RenderModule.cs" company="Nathan Miller">
// Copyright (c) Nathan Miller.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
namespace App.Modules.Render
{
    using System.Collections.Generic;
    using App.Modules.ChangeTrack;
    using App.Modules.Component;
    using App.Modules.Message;
    using App.Modules.Scene;
    using App.Modules.Tool;
    using TileTool.Editor.Grid;
    using TileTool.Editor.Tool.Camera;
    using TileTool.Editor.Tool.Scene;
    using TileTool.Input;
    using TileTool.Log;
    using TileTool.Message;
    using TileTool.Render;
    using TileTool.Scene.Entity;
    using TileTool.Scene.Message;
    using TileTool.Tool;

    /// <summary>
    /// Application render module.
    /// </summary>
    public class RenderModule : Module
    {
        #region Constants - Private

        /// <summary>
        /// Log message group.
        /// </summary>
        private const string LogGroup = "RenderModule";

        #endregion

        #region Properties - Public

        /// <summary>
        /// Gets the application's main canvas.
        /// </summary>
        public ICanvas Canvas
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the camera for the application's main canvas.
        /// </summary>
        public ICamera Camera
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets or sets the grid we should draw. If null, no grid will be drawn.
        /// </summary>
        public IGrid Grid
        {
            get;
            set;
        }

        #endregion

        #region Methods - Public

        /// <summary>
        /// Called when the application is starting up.
        /// </summary>
        public override void Startup()
        {
            LogSystem.LogStartup(LogGroup, "Starting...");

            ComponentModule component = GetModule<ComponentModule>();
            CanvasFactoryComponentBase factory = component.Get<CanvasFactoryComponentBase>(ComponentAliases.Canvas);
            ChangeTrackModule changeModule = GetModule<ChangeTrackModule>();

            LogSystem.LogStartup(LogGroup, "Allocating canvas...");
            this.Canvas = factory.Allocate();
            this.Camera = this.Canvas.CreateCamera();

            this.Canvas.Draw += this.HandleCanvasDraw;
            this.Canvas.Input += this.HandleCanvasInput;

            this.SetupCameraToolFixup();

            changeModule.EntitiesChanged += (IEnumerable<EntityChangedEventArgs> changes) =>
                {
                    this.Canvas.Control.Invalidate();
                };

            base.Startup();
        }

        /// <summary>
        /// Register for messages.
        /// </summary>
        public override void RegisterForMessages()
        {
            base.RegisterForMessages();

            MessageModule messageModule = GetModule<MessageModule>();
            MessageRouter router = messageModule.MessageRouter;

            router.RegisterForMessage<SceneMessage>(this.HandleSceneMessage);
        }

        /// <summary>
        /// Unregister for messages.
        /// </summary>
        public override void UnregisterForMessages()
        {
            base.UnregisterForMessages();

            MessageModule messageModule = GetModule<MessageModule>();
            MessageRouter router = messageModule.MessageRouter;

            router.UnregisterForMessage<SceneMessage>(this.HandleSceneMessage);
        }

        #endregion

        #region Methods - Private

        /// <summary>
        /// Handle the canvas draw event.
        /// </summary>
        /// <param name="canvas">Canvas we are drawing.</param>
        /// <param name="renderer">Canvas renderer.</param>
        private void HandleCanvasDraw(ICanvas canvas, ICanvasRenderer renderer)
        {
            SceneModule sceneModule = GetModule<SceneModule>();
            RenderData renderData = new RenderData();

            renderData.Camera = this.Camera;
            renderData.Canvas = canvas;
            renderData.Renderer = renderer;

            renderer.PushMatrix(this.Camera.Matrix.Invert());

            if (this.Grid != null)
            {
                renderer.DrawGrid(this.Camera, this.Grid.Size, this.Grid.Size);
            }

            renderer.PushState();
            renderer.AntiAlias = true;
            sceneModule.Scene.Draw(renderData);
            renderer.PopState();

            // Draw scene tools.
            ToolModule toolModule = GetModule<ToolModule>();

            foreach (ISceneTool tool in toolModule.SceneTools)
            {
                tool.Draw(renderData);
            }

            renderer.PopMatrix();
        }

        /// <summary>
        /// Handle canvas input.
        /// </summary>
        /// <param name="canvas">Canvas the input came from.</param>
        /// <param name="inputData">Input event data.</param>
        private void HandleCanvasInput(ICanvas canvas, InputData inputData)
        {
            canvas.Control.Invalidate();
        }

        /// <summary>
        /// Setup the fixup function we use to setup camera tools properly.
        /// </summary>
        private void SetupCameraToolFixup()
        {
            ToolModule toolModule = GetModule<ToolModule>();
            IToolManager toolManager = toolModule.ToolManager;

            toolManager.Installed += this.HandleToolInstalled;
            toolManager.Uninstalled += this.HandleToolUninstalled;
        }

        /// <summary>
        /// Called when a tool is being installed.
        /// </summary>
        /// <param name="tool">Tool that is being installed.</param>
        private void HandleToolInstalled(ITool tool)
        {
            ICameraTool cameraTool = tool as ICameraTool;
            if (cameraTool == null)
            {
                return;
            }

            cameraTool.Camera = this.Camera;
        }

        /// <summary>
        /// Called when a tool is being uninstalled.
        /// </summary>
        /// <param name="tool">Tool that is being uninstalled.</param>
        private void HandleToolUninstalled(ITool tool)
        {
            ICameraTool cameraTool = tool as ICameraTool;
            if (cameraTool == null)
            {
                return;
            }

            cameraTool.Camera = null;
        }

        /// <summary>
        /// Handle a scene message.
        /// </summary>
        /// <param name="message">Message to handle.</param>
        /// <returns>Returns if the message was handled or not.</returns>
        private MessageHandlerResult HandleSceneMessage(SceneMessage message)
        {
            // This is shitty.
            this.Canvas.Control.Invalidate();
            return MessageHandlerResult.Ignored;
        }

        #endregion
    }
}
